﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace AroPl.Addons
{
    public class FileAuth
    {
        // <summary>
        /// 计算文件的MD5校验
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, FileMode.Open);
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }

        public static string GetMD5HashFromBytes(byte[] file)
        {
            try
            {
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromBytes() fail,error:" + ex.Message);
            }
        }
    }

    public class AESEncryption
    {
        public static byte[] AesDecryptor(byte[] bsFile, string password)
        {
            RijndaelManaged aes = new RijndaelManaged();
            aes.Key = Encoding.UTF8.GetBytes(password);
            aes.IV = Encoding.UTF8.GetBytes(password.Substring(8, 16));
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;
            ICryptoTransform transform = aes.CreateDecryptor();
            return transform.TransformFinalBlock(bsFile, 0, bsFile.Length);
        }

        public static byte[] AesEncryptor(byte[] bsFile, string password)
        {
            RijndaelManaged aes = new RijndaelManaged();
            aes.Key = Encoding.UTF8.GetBytes(password);
            aes.IV = Encoding.UTF8.GetBytes(password.Substring(8, 16));
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;
            ICryptoTransform transform = aes.CreateEncryptor();
            return transform.TransformFinalBlock(bsFile, 0, bsFile.Length);
        }
    }
}
